from datetime import datetime
import logging
from extensions.ext_database import db
from models.robot.rob_charater import RobCharacter
from models.robot.rob_emoji import RobEmojiPack
from models.robot.rob_timbre import RobTimbre
from models.robot.robots import Robots


class AgentService:
    @staticmethod
    def remote_robot_login(robot_id: str,robot_remote_ip:str) -> dict:
        robot = db.session.get(Robots, robot_id)
        if not robot:
            return {
                "code": "failed",
                "message": "The robot not exist."
            }
        if not robot.activated_at or not robot.extra_info or not robot.extra_info.account_id:
            return {
                "code": "unactivated",
                "message": "The robot not activated."
            }
        character = db.session.get(RobCharacter, robot.cur_charater_id)
        if not character:
            return {
                "code": "failed",
                "message": "The robot character not exist."
            }
        timbre = db.session.get(RobTimbre, robot.cur_timbre_id)
        if not timbre:
            return {
                "code": "failed",
                "message": "The robot timbre not exist."
            }
        if not timbre.provider:
            return {
                "code": "failed",
                "message": "The robot timbre provider not exist."
            }
        try:
            if robot.extra_info:
                robot.extra_info.last_login_at = datetime.now()
                robot.extra_info.last_ip = robot_remote_ip
        except Exception as e:
            db.session.rollback()
            logging.error(f"update robot extra info error.ID:'{robot_id}',{e}",stack_info=True)
        result = {
            "code": "success",
            "data": {
                "timbre": {
                    "timbre_code": timbre.timbre_code,
                    "timbre_provider": timbre.provider.provider_code, 
                    },
                "emoji":{
                    "emotion_predict_agent_id": timbre.emotion_predict_agent_id,
                    "emoji_pack_id": robot.cur_emoji_pack_id,
                },
                "character": {
                    "character_id":  str(character.id),
                    "robot_agent_id": character.agent_id,
                    "personality": character.personality,
                }

                # "wakeup_sentence": character.wakeup_sentences,
            }
        }
        return result

    @staticmethod
    def get_emoji_params(emoji_pack_id: str) -> dict:
        emoji_pack = db.session.get(RobEmojiPack, emoji_pack_id)
        if not emoji_pack:
            return {
                "code": "failed",
                "message": "Emoji pack not found"
            }
        emojis = emoji_pack.get_emojis()
        emoji_params = {"code": "success", "emojis": [
            emoji.to_dict() for emoji in emojis]}
        return emoji_params
